﻿using Desktop.Controls;
using Desktop.Library;
using Google.GData.Client;
using System;
using System.Windows;

namespace StoryWriter
{
    /// <summary>
    /// Interaction logic for EntryEditor.xaml
    /// </summary>
    public partial class EntryEditor : ActivityBase
    {
        #region Constructors

        public EntryEditor(Blog blog, AtomEntry entry)
        {
            InitializeComponent();

            Blog = blog;
            Entry = entry;
            PrepareEntry();
        }

        #endregion

        #region Properties

        private Blog Blog { get; set; }
        private bool IsNew { get; set; }

        private AtomEntry Entry
        {
            get
            {
                return DataContext as AtomEntry;
            }
            set
            {
                DataContext = value;
            }
        }

        #endregion

        #region Methods

        private void PrepareEntry()
        {
            if (Entry == null)
            {
                Entry = new AtomEntry();
                Entry.Content.Type = "html";
                IsNew = true;
            }
            else
            {
                IsNew = false;
            }
        }

        private void Save()
        {
            if (IsNew)
            {
                Entry = Blog.InsertEntry(Entry);
                IsNew = false;
            }
            else
            {
                Entry = Blog.UpdateEntry(Entry);
            }
        }

        #endregion

        #region Event Handlers

        private void ActivityBase_PrincipalChanged(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void acceptButton_Click(object sender, RoutedEventArgs e)
        {
            Save();
            Close();
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void publishButton_Click(object sender, RoutedEventArgs e)
        {
            Entry.Published = DateTime.Now;
            Entry.IsDraft = false;
            Save();
            Close();
        }

        #endregion
    }
}